#ifndef _USERREGISTERSECTION2_HPP
#define _USERREGISTERSECTION2_HPP
#include "TcpConnection.hpp"
#include "TLV.hpp"
#include "Packet.hpp"
#include "MySQLClient.hpp"
#include "logger.hpp"
#include <string>
#include <cstdlib>
#include <ctime>
#include <cstdio>

using namespace wd;
using namespace std;

class UserRegisterSection2{
private:
    TcpConnectionPtr _conn;
    Packet _packet;

public:
    UserRegisterSection2(TcpConnectionPtr conn,Packet p)
    :_conn(conn),_packet(p){}
    ~UserRegisterSection2(){}
    void process(){
        if(_packet.type == TASK_REGISTER_SECTION2) {
            string encrypt=_packet._msg;
            MyLogger::getInstance().serverInfo("用户注册请求部分2密文: " + encrypt);
            string setting=getSetting(encrypt);
            MySQLClient myclient;
            if(myclient.connect("localhost", 3306, "root", "1234","shms"))
            {
                //根据setting去数据库中查找位置，找到后将encrypt写入相对位置的encrypt
                string sql="UPDATE shms_user SET encrypt='" + encrypt + "' WHERE setting='" + setting + "'";
                MyLogger::getInstance().serverInfo("执行SQL: " + sql);
                
                bool updateSuccess = myclient.writeOperationQuery(sql);
                
                // 发送响应
                TLV tlv;
                if(updateSuccess) {
                    MyLogger::getInstance().serverInfo("用户注册第二阶段成功");
                    tlv.type = TASK_LOGIN_SECTION2_RESP_OK;
                    const char* msg = "Register success";
                    tlv.length = strlen(msg);
                    tlv.setData(msg);
                } else {
                    MyLogger::getInstance().serverError("密文写入失败");
                    tlv.type = TASK_REGISTER_SECTION2_RESP_ERROR;
                    const char* msg = "Register failed";
                    tlv.length = strlen(msg);
                    tlv.setData(msg);
                }
                _conn->sendInLoop(tlv);
            } else {
                // 数据库连接失败
                MyLogger::getInstance().dbError("数据库连接失败");
                TLV tlv;
                tlv.type = TASK_LOGIN_SECTION2_RESP_ERROR;
                tlv.length = 0;
                _conn->sendInLoop(tlv);
            }
        }
    }
private:
    string getSetting(const string & msg)
    {
        int i,j;
        //取出salt,i 记录密码字符下标，j记录$出现次数
        for(i = 0,j = 0;msg[i]&& j!=3;++i)
        {
            if(msg[i] == '$')
                ++j;
        }
        return string(msg,0,i);
    }
};

#endif
